<template>
  <div class="checkbox-group">
    <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange"><span class="title">{{groupName}}</span></el-checkbox>
    <div></div>
    <el-checkbox-group v-model="checkedItems" @change="changed">
      <el-checkbox v-for="item in List" :label="item.code" :checked="isChecked(item.code)" :key="item.code">{{item.name}}</el-checkbox>
    </el-checkbox-group>
  </div>
</template>
<script>
  export default {
    data() {
      return {
        checkAll: false,
        checkedItems: [],
        isIndeterminate: true
      };
    },
    model: {
        prop: 'checkedCodes',
        event: 'change'
      },
    props: {
      checkedCodes: {
        type: [String,Array],
      },
      List: {
        type: Array,
        required: true
      },
      groupName: {
        type: String,
        required: true
      }
    },
    computed: {

    },
    methods: {
      handleCheckAllChange(val) {
        this.checkedItems = val ? this.List.map(x=>x.code) : [];
        this.isIndeterminate = false;
        this.$emit('change', this.checkedItems)
      },
      changed(value) {
        let checkedCount = value.length;
        this.checkAll = checkedCount === this.List.length;
        this.isIndeterminate = checkedCount > 0 && checkedCount < this.List.length;
        this.$emit('change', value)
      },
      isChecked(code) {
        let checked = this.checkedCodes || []
        return checked.indexOf(code) !== -1
      }
    }
  };
</script>

<style scoped>
.title {
  font-size: 16px;
  color:#909399;
  font-weight: bold;
}
</style>
